package io.jcode.codegen.service.jboot;

import io.jcode.codegen.utils.FileUtils;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.generator.BaseModelGenerator;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ClassPathSourceFactory;

import java.io.File;
import java.io.IOException;

public class JbootServiceInterfaceGenerator extends BaseModelGenerator {
    private String modelPackage;

    public JbootServiceInterfaceGenerator(String basePackage, String ouputDir) {
        super(basePackage + ".service",
                ouputDir  + File.separator + basePackage.replace(".", File.separator)
                        + File.separator + "service");
        this.modelPackage = basePackage + ".model";
        this.template = "jboot/service/service_template.jf";
    }

    @Override
    protected void initEngine() {
        Engine engine = Engine.create("forService");
        engine.setSourceFactory(new ClassPathSourceFactory());
        engine.addSharedMethod(new StrKit());
        engine.addSharedObject("getterTypeMap", this.getterTypeMap);
        engine.addSharedObject("javaKeyword", this.javaKeyword);
    }

    @Override
    protected void genBaseModelContent(TableMeta tableMeta) {
        Kv data = Kv.by("baseModelPackageName", this.baseModelPackageName);
        data.set("generateChainSetter", this.generateChainSetter);
        data.set("tableMeta", tableMeta);
        data.set("modelPackage", modelPackage);
        data.set("basePackage", this.baseModelPackageName);
        Engine engine = Engine.use("forService");
        tableMeta.baseModelContent = engine.getTemplate(this.template).renderToString(data);
    }

    @Override
    protected void writeToFile(TableMeta tableMeta) throws IOException {
        String target = this.baseModelOutputDir + File.separator + tableMeta.modelName + "Service.java";
        FileUtils.write(target, tableMeta.baseModelContent);
    }
}
